package com.yy.finvideoplayer.manager

import android.util.Log
import android.view.ViewGroup
import android.widget.FrameLayout
import com.google.gson.Gson
import com.yy.finvideoplayer.enum.OperateType
import com.yy.finvideoplayer.ext.dp2pixels
import com.yy.finvideoplayer.ext.orZero
import com.yy.finvideoplayer.model.PlayerOperation
import com.yy.finvideoplayer.model.PlayerOptions
import com.yy.finvideoplayer.utils.JsonUtil
import com.yy.finvideoplayer.videoview.VideoControlView
import com.yy.finvideoplayer.videoview.VideoPlayer

/**
 * @Description: VideoPlayerManager1
 * @Author: yiw89
 * @CreateDate: 2025/9/12 12:15
 * @Version: 1.0
 */
class VideoPlayerManager private constructor(){
    companion object{
        private const val TAG = "videoPlayerManager"
        @JvmStatic
        val instance: VideoPlayerManager by lazy { VideoPlayerManager() }
    }
    private val gson = Gson()
    private val playerMap = mutableMapOf<String, VideoPlayer>()
    private var defaultDecoderType = PlayerOptions.DecoderType.MEDIA_PLAYER


    //region 解码器相关
    /*
        // 设置默认解码器类型
        fun setDefaultDecoderType(decoderType: PlayerOptions.DecoderType) {
            this.defaultDecoderType = decoderType
        }
        // 获取当前应用支持的解码器类型
        fun getSupportedDecoders(): List<PlayerOptions.DecoderType> {
            val supportedList = mutableListOf<PlayerOptions.DecoderType>()

            // MediaPlayer始终支持
            supportedList.add(PlayerOptions.DecoderType.MEDIA_PLAYER)

            // 通过反射检测ExoPlayer
            if (isExoPlayerAvailable()) {
                supportedList.add(PlayerOptions.DecoderType.EXO_PLAYER)
            }

            // 通过反射检测IJKPlayer
            if (isIJKPlayerAvailable()) {
                supportedList.add(PlayerOptions.DecoderType.IJK_PLAYER)
            }
            return supportedList
        }

        private fun isExoPlayerAvailable(): Boolean {
            return try {
                Class.forName("com.google.android.exoplayer2.ExoPlayer")
                true
            } catch (e: ClassNotFoundException) {
                false
            }
        }

        private fun isIJKPlayerAvailable(): Boolean {
            return try {
                Class.forName("tv.danmaku.ijk.media.player.IjkMediaPlayer")
                true
            } catch (e: ClassNotFoundException) {
                false
            }
        }

        // 获取有效的解码器类型（如果指定类型不支持，返回默认类型）
        internal fun getValidDecoderType(requestedType: PlayerOptions.DecoderType): PlayerOptions.DecoderType {
            val supportedDecoders = getSupportedDecoders()
            return if (supportedDecoders.contains(requestedType)) {
                requestedType
            } else {
                defaultDecoderType
            }
        }*/
    //endregion

    //region insertVideoPlayer相关
    fun insertVideoPlayer(params: String, parent: ViewGroup){
        Log.i(TAG, "insertVideoPlayer params = $params")
        val options = try {
            gson.fromJson<PlayerOptions>(params, PlayerOptions::class.java)
        } catch (e: Throwable) {
            e.printStackTrace()
            return
        }
        if (options.src.isNullOrEmpty()) options.src = ""
        addVideoPlayer( options,parent) { result ->
            if (result) {
                //给小程序反馈
                //pageCore.invokeCallback(callbackId, apiOkString("insertVideoPlayer"))
            } else {
                //pageCore.invokeCallback(callbackId, apiFailString("insertVideoPlayer"))
            }
        }?.start()
    }
    private fun addVideoPlayer(options: PlayerOptions,
                               parent: ViewGroup,
                               onComplete: (isSuccessful: Boolean) -> Unit): VideoPlayer? {

        if (playerMap[options.videoPlayerId] != null) {
            onComplete(true)
            return playerMap[options.videoPlayerId]
        }
        val videoPlayer = VideoPlayer(parent.context, playerOption=options).apply {
            //id = R.id.videoView
            tag = options.videoPlayerId
        }
        val layoutParams = FrameLayout.LayoutParams(
            //ViewGroup.LayoutParams.MATCH_PARENT,
            //300.dp2pixels(parent.context)
            options.position?.width?.dp2pixels(parent.context).orZero(),
            options.position?.height?.dp2pixels(parent.context).orZero()
        ).apply {
            leftMargin = options.position?.left?.dp2pixels(parent.context).orZero()
            topMargin = options.position?.top?.dp2pixels(parent.context).orZero()
        }

        // 非同层渲染时，设置圆角
        /*if (!options.isSameLayer) {
            options.style?.borderRadius?.run {
                if (this > 0) {
                    videoPlayer.setViewRadius(this.dp2pixelsF(context))
                }
            }
        }*/

        parent.addView(videoPlayer, layoutParams)
        playerMap[options.videoPlayerId] = videoPlayer
        return videoPlayer
    }
    //endregion


    //region updateVideoPlayer相关
    fun updateVideoPlayer(params: String): Boolean{
        Log.i(TAG, "updateVideoPlayer params = $params")
        val jsonToMap = JsonUtil.jsonToMap(params)
        return updateVideoPlayerInternal(jsonToMap["videoPlayerId"] as String, jsonToMap)
    }
    private fun updateVideoPlayerInternal(playerId: String, updates: Map<String, Any?>): Boolean {
        val videoPlayer: VideoPlayer = playerMap[playerId] ?: return false

        // 获取当前的PlayerOption并更新
        videoPlayer.playerOption.updateWith(updates)

        // 应用更新到VideoPlayer
        videoPlayer.applyOptionUpdates(updates)
        return true
    }
    //endregion

    //region removeVideoPlayer
    fun removeVideoPlayer(params: String): Boolean{
        Log.i(TAG, "deleteVideoPlayer params = $params")
        val jsonToMap = JsonUtil.jsonToMap(params)
        val playerId = jsonToMap["videoPlayerId"] as String
        val videoPlayer: VideoPlayer = playerMap[playerId] ?: return false

        videoPlayer.release()
        playerMap.remove(playerId)
        return true
    }
    //endregion

    //region operateVideoPlayer
    fun operateVideoPlayer(playerId: String, operation: PlayerOperation): Boolean{
        val videoPlayer: VideoPlayer = playerMap[playerId] ?: return false
        when(operation.type){
            OperateType.PLAY.value -> {
                videoPlayer.playOperation()
            }
            OperateType.PAUSE.value -> {
                videoPlayer.pauseOperation()
            }
            OperateType.STOP.value -> {
                videoPlayer.stopOperation()
            }
            OperateType.SEEK.value -> {
                videoPlayer.seekAction(operation.position)
            }
            OperateType.SEND_DANMU.value ->{

                videoPlayer.sendDanmu(operation.text, operation.color)
            }
            OperateType.PLAYBACK_RATE.value ->{
                videoPlayer.playBackRateAction(operation.rate)
            }
            OperateType.REQUEST_FULL_SCREEN.value ->{
                videoPlayer.requestFullScreenAction()
            }
            OperateType.EXIT_FULL_SCREEN.value ->{
                videoPlayer.exitFullScreenAction()
            }
            else -> {
                //Toast.makeText()
            }
        }
        return true
    }
    //endregion
}
